package com.nuanshui.heatedloan.credit.pay.validation;

import com.nuanshui.heatedloan.credit.pay.annotation.ValidationAttribute;
import com.nuanshui.heatedloan.credit.pay.behavior.PayBehavior;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

@Component
public class PayValidationProcessor implements BeanPostProcessor,FactoryBean<PayValidationFacade> {


    private PayValidationFacade payValidationFacade = new PayValidationFacade();
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {

        Class<?> targetClass = AopUtils.getTargetClass(bean);

        ValidationAttribute attribute =  AnnotationUtils.getAnnotation(targetClass, ValidationAttribute.class);

        if(attribute!=null &&  bean instanceof Validation) {
            PayValidationWrapper wrapper = new PayValidationWrapper();
            wrapper.setGroup(attribute.group());
            wrapper.setName(attribute.group());
            wrapper.setTarget((Validation) bean);
            wrapper.setOrder(attribute.order());
            payValidationFacade.registerGroup(wrapper);//过滤器注册
        }

        return bean;
    }

    @Override
    public PayValidationFacade getObject() throws Exception {
        return payValidationFacade;
    }

    @Override
    public Class<?> getObjectType() {
        return PayValidationFacade.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}